<!-- 可显示状态的容器 -->
<template>
  <template v-if="initStatus == 1">
    <slot></slot>
  </template>
  <div v-if="initStatus == 0" v-loading="true" class="loading-view"></div>
  <Placeholder v-if="initStatus == -1" class="error" :title="errorMsg" btn-text="重试" showRetry @retry="runInit" />
</template>
<script setup>
import { ref } from 'vue'

import Placeholder from './Placeholder.vue'
import { onMounted, watch } from 'vue'

const props = defineProps({ init: Function })
const initStatus = ref(0)
const emit = defineEmits(['inited'])
const errorMsg = ref()

watch(initStatus, (val) => {
  if (val === 1) {
    emit('inited')
  }
})
onMounted(() => runInit())
async function runInit() {
  initStatus.value = 0
  errorMsg.value = undefined
  if (!props.init || typeof obj === 'function') {
    initStatus.value = 1
    return
  }
  const initSuccess = await props
    .init()
    .then(() => true)
    .catch((err) => {
      console.error('err :>> ', err)
      errorMsg.value = err.msg || err.message || err
      return false
    })
  initStatus.value = initSuccess ? 1 : -1
}
</script>

<style lang="scss" scoped>
.loading-view {
  height: 100%;
  background-color: #ffffff;
}
</style>
